package com.example.tys.baseapplication.Permission;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

/**
 * PermissionHelper permissionHelper = new PermissionHelper(this, permissionsCallback);
 * permissionHelper.requestPermissions(Manifest.permission.CAMERA, 456);
 *
 * @author tys
 * @date 2019/4/19
 */

public class PermissionHelper {

    protected static final String TAG = "PermissionHelper";
    private final LazySingleton<PermissionsFragment> mPermissionsFragment;


    public PermissionHelper(@NonNull final FragmentActivity activity) {
        this.mPermissionsFragment = getLazySingleton(activity.getSupportFragmentManager(), null);
    }

    public PermissionHelper(@NonNull final Fragment fragment) {
        this.mPermissionsFragment = getLazySingleton(fragment.getChildFragmentManager(), null);
    }

    private LazySingleton<PermissionsFragment> getLazySingleton(android.support.v4.app.FragmentManager fragmentManager,
                                                                PermissionsCallback permissionsCallback) {
        return new LazySingleton<PermissionsFragment>() {
            @Override
            protected PermissionsFragment create() {
                return getPermissionsFragment(fragmentManager, permissionsCallback);
            }
        };
    }


    /**
     * 权限申请
     *
     * @param permissions         permissions {@link Manifest.permission}
     * @param requestCode         请求码
     * @param permissionsCallback 权限申请结果
     */
    public void requestPermissions(@NonNull String permissions, @NonNull Integer requestCode, @NonNull PermissionsCallback permissionsCallback) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            PermissionsFragment permissionsFragment = mPermissionsFragment.get();
            permissionsFragment.setPermissionsCallback(permissionsCallback);
            permissionsFragment.requestPermissions(permissions, requestCode);
        }else {
            permissionsCallback.onRequestPermissionsResult(requestCode, permissions,
                    PackageManager.PERMISSION_GRANTED, false);
        }
    }


    /**
     * 应用设置界面
     * @param requestCode
     * @param callback
     */
    public void toAppSetting(int requestCode, SetAfterCallback callback) {
        PermissionsFragment permissionsFragment = mPermissionsFragment.get();
        permissionsFragment.setAfterSettingCallback(callback);
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                .setData(Uri.fromParts("package", mPermissionsFragment.get().getContext().getPackageName(), null));
        mPermissionsFragment.get().startActivityForResult(intent, requestCode);
    }


    public interface PermissionsCallback {

        /**
         * 权限申请结果
         *
         * @param requestCode                          请求码
         * @param permission                           权限{@link android.Manifest.permission}
         * @param grantResult                          权限申请结果 {@link android.content.pm.PackageManager#PERMISSION_GRANTED}, {@link android.content.pm.PackageManager#PERMISSION_DENIED}
         * @param shouldShowRequestPermissionRationale 是否显示申请理由  true:权限被拒绝，没有选择不再提示  false:权限被拒绝，并且选择不再提示或权限被同意
         */
        void onRequestPermissionsResult(int requestCode, String permission, int grantResult, boolean shouldShowRequestPermissionRationale);
    }

    public interface SetAfterCallback {

        /**
         * 设置界面返回(此时不一定打开权限)
         *
         * @param requestCode 请求码
         */
        void onAppSetAfter(int requestCode);
    }


    abstract class LazySingleton<T> {
        private T mInstance;

        protected abstract T create();

        public final T get() {
            synchronized (this) {
                if (mInstance == null) {
                    mInstance = create();
                }
                return mInstance;
            }
        }
    }

    private PermissionsFragment getPermissionsFragment(@NonNull final android.support.v4.app.FragmentManager fragmentManager, PermissionsCallback permissionsCallback) {
        PermissionsFragment permissionsFragment = findPermissionsFragment(fragmentManager);
        boolean isNewInstance = permissionsFragment == null;
        if (isNewInstance) {
            permissionsFragment = new PermissionsFragment();
            fragmentManager
                    .beginTransaction()
                    .add(permissionsFragment, TAG)
                    .commitNow();
        }
        permissionsFragment.setPermissionsCallback(permissionsCallback);
        return permissionsFragment;
    }

    private PermissionsFragment findPermissionsFragment(android.support.v4.app.FragmentManager fragmentManager) {
        return (PermissionsFragment) fragmentManager.findFragmentByTag(TAG);
    }


}
